package com.mjk.manager.centerconf;

import com.mjk.common.core.redis.datatype.RedisHashUtils;
import com.mjk.common.core.redis.listener.annotation.BeeRedisListener;
import com.mjk.common.core.redis.listener.annotation.RedisKeyEvent;
import com.mjk.common.util.ObjectUtils;
import com.mjk.manager.centerconf.conf.CenterConf;
import com.mjk.manager.centerconf.type.RefreshType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@ConditionalOnProperty(name = "bee.redis", havingValue = "true")
public class ConfCenterListener {
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private CenterConf conf;
	/**
	 * 监听redis 配置中的数据变化
     */
	@SuppressWarnings({"unchecked" })
	@BeeRedisListener(evnet= RedisKeyEvent.UPDATE)
	public void configurationUpdate(String key){	
		if(CenterConf.CONFIGURATION_KEY.equals(key)){
			List<String> keys = RedisHashUtils.getKeys(redisTemplate, CenterConf.CONFIGURATION_CONTENT_KEY);
			Map<String,Object> tmpMap = new HashMap<>();
			for(String k : keys){
				Object obj = RedisHashUtils.get(redisTemplate, CenterConf.CONFIGURATION_CONTENT_KEY, k);	
				if(ObjectUtils.isNotEmpty(obj)&&obj.equals(conf.getMap().get(k))){
					//如果一样不需要更新
				}else{
					//获取变更数据					
					tmpMap.put(k, obj);
					//更新properties里面的数据
					conf.getMap().put(k, obj);
				}
			}
			//刷新
			RefreshType.doRefresh(conf.getContext(), tmpMap, new HashMap<>(conf.getMap()));
		}		
	}
}
